//
//  realPersonAuthenticationSubTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/11/1.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "RealComplayAuthenticationSubTabVC.h"
#import "RealComplayAuthenticationSonTabVC.h"
#import "WriteRequirementTitleCell.h"
#import "UpdateImageSubCell.h"
#import "ButtonCell.h"
#import "AuthenticationModel.h"
#import "CustomePickerImageVC.h"
#import "TZImagePickerController.h"
#import "MyCollectionVC.h"
@interface realPersonAuthenticationSubTabVC ()<ButtonCellDelegate,UpdateImageSubCellDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>
@property(nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,strong) NSDictionary *dict;
@end
static NSString *identifierTitle = @"WriteRequirementTitleCell";
static NSString *identifierUpdateImage = @"UpdateImageSubCell";
static NSString *identifierBtn = @"ButtonCell";
@implementation realPersonAuthenticationSubTabVC

- (void)viewDidLoad {
    [super viewDidLoad];
    if (!self.realPerson) {
        self.navigationItem.title = @"企业实名认证";
    }else {
        self.navigationItem.title = @"个人实名认证";
    }
    [self.tableView registerNib:[UINib nibWithNibName:@"WriteRequirementTitleCell" bundle:nil] forCellReuseIdentifier:identifierTitle];
    [self.tableView registerNib:[UINib nibWithNibName:@"UpdateImageSubCell" bundle:nil] forCellReuseIdentifier:identifierUpdateImage];
    [self.tableView registerNib:[UINib nibWithNibName:@"ButtonCell" bundle:nil] forCellReuseIdentifier:identifierBtn];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(simplecertificationinsert:) name:@"simplecertificationinsert" object:nil];
}

- (void)setShowMsg:(BOOL)showMsg
{
    _showMsg = showMsg;
    if (showMsg) {
        [self.tableView reloadData];
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!self.realPerson) {
        return 4;
    }else {
        return 5;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
     if (!self.realPerson) {
         if (indexPath.row == 0) {
             WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTitle forIndexPath:indexPath];
             cell.titleL.text = @"上传法人身份证明";
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
             return cell;
         }else if (indexPath.row == 1||indexPath.row == 2) {
             UpdateImageSubCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierUpdateImage forIndexPath:indexPath];
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
             cell.indexPath = indexPath;
             if (indexPath.row == 1) {
                 cell.frontL.text = @"身份证人像面";
                 if (self.showMsg) {
                     cell.userInteractionEnabled = NO;
                     self.authenticationModel = self.authModel;
                 }
                 self.authenticationModel.idcardfront.length != 0?  cell.authenticationModel = self.authenticationModel:0;
             }else {
                 cell.frontL.text = @"身份证国徽面";
                 if (self.showMsg) {
                     cell.userInteractionEnabled = NO;
                     self.authenticationModel = self.authModel;
                 }
//                 self.authenticationModel.idcardback.length == 0?1:2;
                 self.authenticationModel.idcardback.length != 0?  cell.authenticationModel = self.authenticationModel:0;
             }
             cell.delegate = self;
             return cell;
         }else {
             ButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierBtn forIndexPath:indexPath];
             [cell.btn setTitle:@"下一步" forState:UIControlStateNormal];
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
             cell.delegate = self;
             return cell;
         }
     }else {
         if (indexPath.row == 0) {
             WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTitle forIndexPath:indexPath];
             cell.titleL.text = @"上传或拍摄认证照片";
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
             return cell;
         }else if (indexPath.row == 1||indexPath.row == 2||indexPath.row == 3) {
             UpdateImageSubCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierUpdateImage forIndexPath:indexPath];
             cell.clickFrontBtn.layer.borderColor  = [UIColor colorWithRed:151/255.0 green:193/255.0 blue:91/255.0 alpha:1].CGColor;
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
             cell.indexPath = indexPath;
             cell.delegate = self;
             if (indexPath.row == 1) {
                 cell.frontL.text = @"身份证人像面";
                 if (self.showMsg) {
                     cell.userInteractionEnabled = NO;
                     self.authenticationModel = self.authModel;
                 }
                 self.authenticationModel.idcardfront.length == 0? [cell.clickFrontBtn setImage:[UIImage imageNamed:@"uploading"] forState:UIControlStateNormal]:0;
                 self.authenticationModel.idcardfront.length != 0?  cell.authenticationModel = self.authenticationModel:0;
             }else  if (indexPath.row == 2) {
                 cell.frontL.text = @"身份证国徽面";
                 if (self.showMsg) {
                     cell.userInteractionEnabled = NO;
                     self.authenticationModel = self.authModel;
                 }
                 self.authenticationModel.idcardback.length == 0? [cell.clickFrontBtn setImage:[UIImage imageNamed:@"uploading"] forState:UIControlStateNormal]:0;
                 self.authenticationModel.idcardback.length != 0?  cell.authenticationModel = self.authenticationModel:0;
             }else {
                 cell.frontL.text = @"手持身份证人像面半身照";
                 if (self.showMsg) {
                     cell.userInteractionEnabled = NO;
                     self.authenticationModel = self.authModel;
                 }
                 self.authenticationModel.hpcardicon.length == 0? [cell.clickFrontBtn setImage:[UIImage imageNamed:@"uploading"] forState:UIControlStateNormal]:0;
                 self.authenticationModel.hpcardicon.length != 0?  cell.authenticationModel = self.authenticationModel:0;
             }
             return cell;
         }else {
             ButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierBtn forIndexPath:indexPath];
             [cell.btn setTitle:@"提交审核" forState:UIControlStateNormal];
             [cell.btn setBackgroundColor:[UIColor colorWithRed:151/255.0 green:193/255.0 blue:91/255.0 alpha:1]];
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
             cell.delegate = self;
             if (self.showMsg) {
                 cell.btn.hidden = YES;
             }
             return cell;
         }
     }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.realPerson) {
        if (indexPath.row == 0) {
            return 60;
        }else if(indexPath.row == 1||indexPath.row == 2) {
            return 200;
        }else{
            return 80;
        }
    }else {
        if (indexPath.row == 0) {
            return 60;
        }else if(indexPath.row == 1||indexPath.row == 2||indexPath.row == 3) {
            return 200;
        }else{
            return 80;
        }
    }
    
}
#pragma mark-代理:上传身份证
- (void)updateImageSubCell:(UpdateImageSubCell *)updateImageSubCell withBtn:(UIButton *)btn withIndexPath:(NSIndexPath *)indexPath
{
//    if (!self.realPerson) {
//
//    }else {
//
//    }
    if (indexPath.row == 1) {
        
    }else {
        
    }
    self.indexPath = indexPath;
    //打开照相机和图片
    UIAlertController *sheetControler = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    CustomePickerImageVC *picker = [[CustomePickerImageVC alloc]init];
    
    picker.edgesForExtendedLayout =  UIRectEdgeNone;
    picker.automaticallyAdjustsScrollViewInsets = NO;
    
    picker.allowsEditing = YES;
    
    picker.delegate = self;
    sheetControler.popoverPresentationController.sourceView = self.view;
    sheetControler.popoverPresentationController.sourceRect = self.view.frame;
    [self pushTZImagePickerController];
    [self presentViewController:sheetControler animated:YES completion:nil] ;
}
- (void)pushTZImagePickerController {
    UpdateImageSubCell *cell = [self.tableView cellForRowAtIndexPath:self.indexPath];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlString = @"http://www.qichangkeji.vip/upload/upload?savePath=img";
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    //    imagePickerVc.allowPickingVideo = self.allowPickingVideoSwitch.isOn;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowTakePicture = YES;
    imagePickerVc.allowPickingMultipleVideo = NO; // 是否可以多选视频
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = YES;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        XLog(@"photos:%@",photos);
        /**
         2018-12-06 16:07:48.463518+0800 BusinessMarket[789:89872] photos:(
         "<UIImage: 0x2829bd340> size {750, 1206} orientation 0 scale 1.000000"
         )
         */
        UIImage *image = photos[0];
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        [cell.clickFrontBtn setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        //选择回调
        self.tableView.userInteractionEnabled = NO;
        [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            //
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
            //二进制文件，接口key值，文件路径，图片格式
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            float update = uploadProgress.fractionCompleted*100;
            XLog(@"%f",update);
            XLog(@"%.f%%",update);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [WSProgressHUD showWithStatus:[NSString stringWithFormat:@"%.f%%",update]];
                
            });
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            NSString *stringImg = [responseObject mj_JSONString];
            NSDictionary *dict = [stringImg mj_JSONObject];
            XLog(@"stringImg:%@",stringImg);
            if (self.indexPath.row == 1) {
                self.authenticationModel.idcardfront = [dict objectForKey:@"path"];
            }else  if (self.indexPath.row == 2) {
                self.authenticationModel.idcardback = [dict objectForKey:@"path"];
            }else {
                self.authenticationModel.hpcardicon = [dict objectForKey:@"path"];
            }
            
            [WSProgressHUD dismiss];
            self.tableView.userInteractionEnabled = YES;
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [WSProgressHUD dismiss];
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"图片上传失败,请重新上传"];
            self.tableView.userInteractionEnabled = YES;
        }];
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    
    // 提前定位
    __weak typeof(self) weakSelf = self;
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePickerVc = [[UIImagePickerController alloc] init];
        imagePickerVc.delegate = self;
        imagePickerVc.sourceType = sourceType;
        
        //        NSMutableArray *mediaTypes = [NSMutableArray array];
        //        if (self.showTakePhotoBtnSwitch.isOn) {
        //            [mediaTypes addObject:(NSString *)kUTTypeImage];
        //        }
        //        if (mediaTypes.count) {
        //            _imagePickerVc.mediaTypes = mediaTypes;
        //        }
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    } else {
        //        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    tzImagePickerVc.sortAscendingByModificationDate = YES;
    [tzImagePickerVc showProgressHUD];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    
    NSIndexPath *indexPath = [[NSIndexPath alloc]init];
    if (!self.realPerson) {
        indexPath = [NSIndexPath indexPathForRow:7 inSection:0];
    }else {
    }
    UpdateImageSubCell *cell = [self.tableView cellForRowAtIndexPath:self.indexPath];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    [cell.clickFrontBtn setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *urlString = @"http://www.qichangkeji.vip/upload/upload?savePath=img";
    //选择回调
//    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
//    [WSProgressHUD show];
    self.tableView.userInteractionEnabled = NO;
    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        //二进制文件，接口key值，文件路径，图片格式
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        XLog(@"%f",uploadProgress.fractionCompleted);
        float update = uploadProgress.fractionCompleted*100;
        XLog(@"%f",update);
        XLog(@"%.f%%",update);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WSProgressHUD showWithStatus:[NSString stringWithFormat:@"%.f%%",update]];
            
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"responseObject:%@",responseObject);
        NSString *stringImg = [responseObject mj_JSONString];
        NSDictionary *dict = [stringImg mj_JSONObject];
        XLog(@"stringImg:%@",stringImg);
        if (self.indexPath.row == 1) {
            self.authenticationModel.idcardfront = [dict objectForKey:@"path"];
        }else  if (self.indexPath.row == 2) {
            self.authenticationModel.idcardback = [dict objectForKey:@"path"];
        }else {
            self.authenticationModel.hpcardicon = [dict objectForKey:@"path"];
        }
        [WSProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WSProgressHUD dismiss];
        [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"图片上传失败,请重新上传"];
        self.tableView.userInteractionEnabled = YES;
    }];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark-代理---下一步
- (void)buttonCell:(ButtonCell *)buttonCell withClickBtn:(UIButton *)clickBtn
{
    if (!self.realPerson) {
        if (!self.showMsg) {
            if (self.authenticationModel.idcardfront.length == 0) {
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请上传身份证人像面"];
            }else if (self.authenticationModel.idcardback.length == 0) {
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请上传身份证国徽面"];
            }else {
                realPersonAuthenticationSonTabVC *vc = [[realPersonAuthenticationSonTabVC alloc]init];
                vc.authenticationModel = self.authenticationModel;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else {
            realPersonAuthenticationSonTabVC *vc = [[realPersonAuthenticationSonTabVC alloc]init];
            vc.showMsg = self.showMsg;
            vc.authModel = self.authModel;
            vc.authenticationModel = self.authenticationModel;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else {
#warning 个人认证
        XLog(@"self.authenticationModel.idcardfront:%@",self.authenticationModel.idcardfront);
        if (self.authenticationModel.idcardfront.length == 0) {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请上传身份证人像面"];
        }else if (self.authenticationModel.idcardback.length == 0) {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请上传身份证国徽面"];
        }else if (self.authenticationModel.hpcardicon.length == 0) {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"请上传手持身份证人像面半身照"];
        }else {
            self.dict = @{
                          @"uid":[UserDefaultsHelper readUid],
                          @"name":self.authenticationModel.name,
                          @"idnum":self.authenticationModel.idnum,
                          @"idcardfront":self.authenticationModel.idcardfront,
                          @"idcardback":self.authenticationModel.idcardback,
                          @"hpcardicon":self.authenticationModel.hpcardicon,
                          @"token":[UserDefaultsHelper readToken]
                          };
            XLog(@"dict:%@",self.dict);
            [CustomeManager POSTWithURLIndex:43 parameters:self.dict success:^(NSDictionary *dict) {
                XLog(@"dict:%@",dict);
            } failure:^(NSError *error) {
                XLog(@"error:%@",error);
            }];
        }
    }
}

-(void)simplecertificationinsert:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSString *message = [info.userInfo objectForKey:@"message"];
    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[MyCollectionVC class]]) {
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
    });

    
    
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
